﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace BackupMirthToTFS
{
    public static class Mirth
    {
        public static dynamic CallMirthSystemForFullBackup(MirthBackup mirthTarget)
        {            
            string resultFile = RunCmd(mirthTarget.MirthHost, mirthTarget.MirthUserName, mirthTarget.MirthUserPwd);
            bool successfulBackup = false;
            try
            {
                var fileLen = new System.IO.FileInfo(resultFile).Length;
                successfulBackup = (new System.IO.FileInfo(resultFile).Length > 0);
            }
            catch (Exception) { }

            return new
            {
                Success = successfulBackup,
                BackupFile = resultFile,
                MirthBackup = mirthTarget
            };
        }

        public static string RunCmd(string server, string username, string pwd)
        {
            const string backupBatchFile = "Backup.bat";
            const string MirthPath = @"C:\Program Files\Mirth";
            const string StartFileName = "java";
            const string JavaExecParams = @"-jar shell-launcher.jar shell-launcher.xml -a https://{0}:8443 -u {1} -p {2} -v 0.0.0 -s {3}";
            const string ExportConfigCommand = @"exportcfg ""{0}""";

            string targetBackupFile = Path.Combine(Environment.CurrentDirectory,
                                                   "{0}-{1}.xml".FormatWith( server, DateTime.Now.PrettyFormat()));

            //create backup.bat to the mirth working dir. this is how we issue the command to backup the server config to one file.            
            using (var file = File.CreateText(Path.Combine(MirthPath, backupBatchFile)))
            {
                file.Write(ExportConfigCommand.FormatWith(targetBackupFile));
                file.Flush();
            }

            using (var proc = new System.Diagnostics.Process())
            {
                proc.EnableRaisingEvents = false;
                proc.StartInfo.FileName = StartFileName;
                proc.StartInfo.WorkingDirectory = MirthPath;
                proc.StartInfo.Arguments = JavaExecParams.FormatWith(server, username, pwd, backupBatchFile); 
                proc.Start();
                proc.WaitForExit();
            }

            return targetBackupFile;
        }
    }
}
